<template>
  <div>
    <a-spin :spinning="isLoadingOther">
      <a-form ref="formSearchRef" name="advanced_search" class="ant-advanced-search-form" :model="formSearchField">
        <a-row :gutter="24">
          <a-col :span="formSearchColSpan">
            <a-form-item name="title" label="标题">
              <a-input v-model:value="formSearchField.title" placeholder="请输入标题" style="width: 95%;" />
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan">
            <a-form-item name="donation_id" label="捐赠项目">
              <a-select v-model:value="formSearchField.donation_id" show-search option-filter-prop="search-value"
                placeholder="请选择捐赠项目" style="width: 95%;" @change="handleDonationIdChange">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="(item, index) in donationList" :key="index" :value="index"
                  :search-value="item">{{ item
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan" v-show="formSearchExpand">
            <a-form-item name="author" label="发布人">
              <a-input v-model:value="formSearchField.author" placeholder="请输入标题" style="width: 95%;" />
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan" v-show="formSearchExpand">
            <a-form-item name="status" label="状态">
              <a-select v-model:value="formSearchField.status" placeholder="请选择状态" style="width: 95%;">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="(item, index) in statusMap" :key="index" :value="index">{{ item
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan">
            <a-button type="primary" html-type="submit" @click="doSearchForm">搜索</a-button>
            <a-button style="margin: 0 8px" @click="resetFormRef">重置</a-button>
            <a-button style="margin-right: 8px" @click="editData(0)"
              v-if="adminCheckOption('donation', 'donation_progress', 'add')">新增</a-button>
            <a-button type="link" @click="formSearchExpandChg" v-if="!formSearchExpand">更多搜索</a-button>
            <a-button type="link" @click="formSearchExpandChg" v-if="formSearchExpand">收起</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <a-table bordered :data-source="dataListSource" :columns="dataListColumns" :loading="isLoading"
      @change="dataTableChange" rowKey="id" :pagination="tablePagination">
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'donation_title'">
          {{ record.donation.title }}
        </template>
        <template v-if="column.dataIndex === 'status_text'">
          <span style="color: red;" v-if="record.status === 2">{{ text }}</span>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a-tag color="blue" @click="editData(record.id)"
            v-if="adminCheckOption('donation', 'donation_progress', 'edit')">编辑</a-tag>
          <a-popconfirm title="确认要删除吗？" @confirm="onChangeStatus(record.id, 2, index)"
            v-if="adminCheckOption('donation', 'donation_progress', 'delete') && record.status === 1">
            <a-tooltip color="red" placement="rightTop">
              <template #title>
                <span>当前是正常状态，点击可删除此数据</span>
              </template>
              <a-tag color="green">删除</a-tag>
            </a-tooltip>
          </a-popconfirm>
          <a-popconfirm title="确认要恢复此数据吗？" @confirm="onChangeStatus(record.id, 1, index)"
            v-if="adminCheckOption('donation', 'donation_progress', 'undelete') && record.status === 2">
            <a-tooltip color="green" placement="leftTop">
              <template #title>
                <span>当前是已删除状态，点击可重置为正常状态</span>
              </template>
              <a-tag color="red">恢复正常</a-tag>
            </a-tooltip>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { reactive, ref, inject, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue'
import { getDonationProgressList, chgDonationProgressStatus, getDonationListAll } from "@/api/admin"   //引入api
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();

const { adminCheckOption } = inject('adminCheckOption');  // 依赖注入--权限校验函数

const formSearchColSpan = ref(8);  // 搜索--每个搜索项暂用宽度（共24宽度）
const isLoading = ref(false);    // 控制loading
const isLoadingOther = ref(false);    // 控制loading
const formSearchExpand = ref(false);    // 搜索--是否展开更多
const dataListSource = ref([]); // 数据列表
const dataTotal = ref(0);    // 符合条件的数据总数
const formSearchRef = ref();  // 表单搜索,ref对象
const currentPage = ref(1);  // 当前页码
const pageSize = ref(10);      // 每页显示条数
const statusMap = reactive({
  1: '正常',
  2: '已删除'
});  //状态映射

// 表格分页
const tablePagination = computed(() => ({
  total: dataTotal.value,
  current: currentPage.value,
  pageSize: pageSize.value,
  showTotal: (total, range) => `第 ${range[0]} 至 ${range[1]} 条数据，共 ${total} 条数据`
}));
// 数据列表字段
const dataListColumns = [
  {
    title: '捐赠项目',
    dataIndex: 'donation_title',
    ellipsis: true,
    ellipsis: true,
  },
  {
    title: '发布人',
    dataIndex: 'author',
    width: 160
  },
  {
    title: '项目进展日期',
    dataIndex: 'add_date',
    width: 140
  },
  {
    title: '标题',
    dataIndex: 'title',
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'status_text',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 180
  },
];
// 表单搜索字段
const formSearchField = reactive({
  page: currentPage.value,  //当前页码（current的值改变后，这里的值不会跟着改变，需要手动赋值）
  limit: pageSize.value,  //每页条数（pageSize的值改变后，这里的值不会跟着改变，需要手动赋值）
  title: '',
  author: '',
  donation_id: null,
  status: null,
});

// 表单搜索方法
const doSearchForm = () => {
  currentPage.value = 1;
  getDataList();
};

// 获取接口数据列表
const getDataList = () => {
  isLoading.value = true;

  formSearchField.page = currentPage.value;  //当前页码（current的值改变后，这里的值不会跟着改变，需要手动赋值）
  formSearchField.limit = pageSize.value;  //每页条数（pageSize的值改变后，这里的值不会跟着改变，需要手动赋值）

  getDonationProgressList(formSearchField).then((res) => {
    isLoading.value = false;
    if (res === false) return;

    dataListSource.value = res.data;  //数据列表
    dataTotal.value = res.count;  //总条数

    message.success('获取成功');
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 重置表单搜索
const resetFormRef = () => {
  formSearchRef.value.resetFields();
  currentPage.value = 1;
  getDataList();
};

// 修改数据状态
const onChangeStatus = (id, newStatus, dataIndex) => {
  isLoading.value = true;

  // 提交的数据
  let chgData = {
    id: id,
    status: newStatus
  };

  chgDonationProgressStatus(chgData).then((res) => {
    isLoading.value = false;
    if (res === false) return;

    // 修改数据状态，用于展示修改后的数据
    dataListSource.value[dataIndex].status = newStatus;
    dataListSource.value[dataIndex].status_text = statusMap[newStatus];

    message.success('操作成功');
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 数据列表分页、排序、过滤
const dataTableChange = (pagination, filters, sorter) => {
  currentPage.value = pagination.current;
  getDataList();
};

// 新增、编辑数据
const editData = (id) => {
  router.push({name: 'admin_donation_progress_edit', query: { id: id }});
};

// 搜索--展开/收起更多搜索项
const formSearchExpandChg = () => {
  formSearchExpand.value = !formSearchExpand.value;
};

const donationList = ref([]); // 捐赠项目列表
// 获取捐赠项目列表
const getDonationList = () => {
  isLoadingOther.value = true;
  getDonationListAll({}).then((res) => {
    isLoadingOther.value = false;
    if (res === false) return;

    donationList.value = res.data;  //数据列表
  });
};

// 捐赠项目选择变化
const handleDonationIdChange = (value) => {
  getDataList();
}


// 页面加载完成后，获取数据列表
onMounted(() => {
  getDonationList();
  getDataList();
})
</script>

<style scoped></style>